package org.monster.context.core.filter;

import org.monster.context.core.parameter.HttpResponse;
import org.monster.context.core.request.HttpRequest;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

/**
 * 应用过滤器通道
 *
 * @author Monster
 */
public class ApplicationFilterChain implements FilterChain {

    /**
     * 派遣
     */
    public static boolean dispatch = false;
    /**
     * 请求
     */
    private static HttpRequest request = null;
    /**
     * 响应
     */
    private static HttpResponse response = null;
    /**
     * 过滤器
     */
    private List<Filter> filters = null;
    /**
     * 索引
     */
    private int index = 0;

    /**
     * 构造方法
     */
    public ApplicationFilterChain() {
        super();
    }

    /**
     * 构造方法
     *
     * @param filters 过滤器 集合
     */
    public ApplicationFilterChain(List<Filter> filters) {
        this.filters = filters;
    }

    /**
     * 设置 请求
     *
     * @param request 请求
     */
    public static void setRequest(HttpRequest request) {
        ApplicationFilterChain.request = request;
    }

    /**
     * 设置 响应
     *
     * @param response 响应
     */
    public static void setResponse(HttpResponse response) {
        ApplicationFilterChain.response = response;
    }

    /**
     * 添加 过滤器 集合
     *
     * @param filters 过滤器 集合
     */
    public void addFilters(List<Filter> filters) {
        this.filters = filters;
    }

    /**
     * 遍历过滤器形成后进先出的链
     *
     * @param request  请求
     * @param response 响应
     * @throws IOException      输入输出异常
     * @throws ServletException 服务者异常
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (dispatch) {
            if (index == filters.size()) {
                dispatch = false;
                return;
            }
            Filter filter = filters.get(index);
            index++;
            filter.doFilter(ApplicationFilterChain.request, ApplicationFilterChain.response, this);
        } else {
            if (index == filters.size()) {
                return;
            }
            Filter filter = filters.get(index);
            index++;
            filter.doFilter(request, response, this);
        }
    }

}
